/**
 * 
 */
package com.music.auth.controllers;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import static com.music.auth.constants.AuthConstants.*;
/**
 * @author asanthan
 *
 */
public class LoginController implements Controller {

	private String mViewName;
	private String mHomePage;
	
	
	public ModelAndView handleRequest(HttpServletRequest pRequest,HttpServletResponse pResponse) 
					throws ServletException, IOException {
		ModelAndView modelAndView = new ModelAndView();
		
		String returnUrl = pRequest.getParameter(PARAM_RETURN_URL);
		if( returnUrl == null){
			returnUrl = getHomePage();
		}
		UserService userService = UserServiceFactory.getUserService();
        
        if(userService != null && userService.getCurrentUser() != null){
        	pResponse.sendRedirect(getHomePage());
        	return modelAndView;
        }
        
        
        String googleLoginUrl = userService.createLoginURL(returnUrl);
		
		modelAndView.addObject(LOGIN_URL,googleLoginUrl);
		modelAndView.setViewName(getViewName());
		
		return modelAndView;
	}


	/**
	 * @return the viewName
	 */
	public String getViewName() {
		return mViewName;
	}


	/**
	 * @param pViewName the viewName to set
	 */
	public void setViewName(String pViewName) {
		mViewName = pViewName;
	}


	/**
	 * @return the homePage
	 */
	public String getHomePage() {
		return mHomePage;
	}


	/**
	 * @param pHomePage the homePage to set
	 */
	public void setHomePage(String pHomePage) {
		mHomePage = pHomePage;
	}
	
	
}